// 标签页右键菜单组件
// 提供关闭、关闭其他、关闭所有、复制路径等操作

import React, { useCallback } from 'react';
import { 
  X, 
  XCircle, 
  Copy, 
  FolderOpen, 
  Save, 
  RotateCcw,
  ArrowRight,
  ArrowLeft,
  Trash2
} from 'lucide-react';
import { useTabStore, Tab, TabStatus } from '../stores/tabStore';
import { cn } from '../utils/cn';

// 菜单项接口
interface MenuItem {
  id: string;
  label: string;
  icon: React.ReactNode;
  shortcut?: string;
  disabled?: boolean;
  danger?: boolean;
  separator?: boolean;
  onClick: () => void;
}

// 右键菜单属性
interface TabContextMenuProps {
  tabId: string;
  x: number;
  y: number;
  onClose: () => void;
}

// 标签页右键菜单组件
export const TabContextMenu: React.FC<TabContextMenuProps> = ({
  tabId,
  x,
  y,
  onClose,
}) => {
  const {
    tabs,
    tabOrder,
    activeTabId,
    closeTab,
    closeAllTabs,
    closeOtherTabs,
    closeTabsToRight,
    closeTabsToLeft,
    saveTab,
    saveAllTabs,
    reopenClosedTab,
    history,
  } = useTabStore();

  const tab = tabs.get(tabId);
  const tabIndex = tabOrder.indexOf(tabId);
  const isModified = tab?.status === TabStatus.Modified;
  const hasUnsavedTabs = Array.from(tabs.values()).some(t => t.status === TabStatus.Modified);
  const canReopenClosed = history.closedTabs.length > 0;

  // 复制文件路径到剪贴板
  const copyPath = useCallback(async () => {
    if (tab) {
      try {
        await navigator.clipboard.writeText(tab.filePath);
      } catch (error) {
        console.error('Failed to copy path:', error);
      }
    }
    onClose();
  }, [tab, onClose]);

  // 在文件管理器中显示
  const showInExplorer = useCallback(() => {
    if (tab) {
      // 这里应该调用Tauri API打开文件管理器
      console.log('Show in explorer:', tab.filePath);
    }
    onClose();
  }, [tab, onClose]);

  // 保存文件
  const handleSave = useCallback(async () => {
    if (tab) {
      await saveTab(tab.id);
    }
    onClose();
  }, [tab, saveTab, onClose]);

  // 保存所有文件
  const handleSaveAll = useCallback(async () => {
    await saveAllTabs();
    onClose();
  }, [saveAllTabs, onClose]);

  // 关闭标签页
  const handleClose = useCallback(async () => {
    await closeTab(tabId);
    onClose();
  }, [closeTab, tabId, onClose]);

  // 关闭其他标签页
  const handleCloseOthers = useCallback(async () => {
    await closeOtherTabs(tabId);
    onClose();
  }, [closeOtherTabs, tabId, onClose]);

  // 关闭所有标签页
  const handleCloseAll = useCallback(async () => {
    await closeAllTabs();
    onClose();
  }, [closeAllTabs, onClose]);

  // 关闭右侧标签页
  const handleCloseToRight = useCallback(async () => {
    await closeTabsToRight(tabId);
    onClose();
  }, [closeTabsToRight, tabId, onClose]);

  // 关闭左侧标签页
  const handleCloseToLeft = useCallback(async () => {
    await closeTabsToLeft(tabId);
    onClose();
  }, [closeTabsToLeft, tabId, onClose]);

  // 重新打开已关闭的标签页
  const handleReopenClosed = useCallback(() => {
    reopenClosedTab();
    onClose();
  }, [reopenClosedTab, onClose]);

  if (!tab) return null;

  // 构建菜单项
  const menuItems: MenuItem[] = [
    // 保存相关
    {
      id: 'save',
      label: '保存',
      icon: <Save size={16} />,
      shortcut: 'Ctrl+S',
      disabled: !isModified,
      onClick: handleSave,
    },
    {
      id: 'save-all',
      label: '保存所有',
      icon: <Save size={16} />,
      shortcut: 'Ctrl+Shift+S',
      disabled: !hasUnsavedTabs,
      onClick: handleSaveAll,
    },
    {
      id: 'separator-1',
      label: '',
      icon: null,
      separator: true,
      onClick: () => {},
    },
    
    // 关闭相关
    {
      id: 'close',
      label: '关闭',
      icon: <X size={16} />,
      shortcut: 'Ctrl+W',
      onClick: handleClose,
    },
    {
      id: 'close-others',
      label: '关闭其他',
      icon: <XCircle size={16} />,
      disabled: tabOrder.length <= 1,
      onClick: handleCloseOthers,
    },
    {
      id: 'close-to-right',
      label: '关闭右侧',
      icon: <ArrowRight size={16} />,
      disabled: tabIndex === tabOrder.length - 1,
      onClick: handleCloseToRight,
    },
    {
      id: 'close-to-left',
      label: '关闭左侧',
      icon: <ArrowLeft size={16} />,
      disabled: tabIndex === 0,
      onClick: handleCloseToLeft,
    },
    {
      id: 'close-all',
      label: '关闭所有',
      icon: <Trash2 size={16} />,
      danger: true,
      onClick: handleCloseAll,
    },
    {
      id: 'separator-2',
      label: '',
      icon: null,
      separator: true,
      onClick: () => {},
    },
    
    // 重新打开
    {
      id: 'reopen-closed',
      label: '重新打开已关闭的标签页',
      icon: <RotateCcw size={16} />,
      disabled: !canReopenClosed,
      onClick: handleReopenClosed,
    },
    {
      id: 'separator-3',
      label: '',
      icon: null,
      separator: true,
      onClick: () => {},
    },
    
    // 文件操作
    {
      id: 'copy-path',
      label: '复制路径',
      icon: <Copy size={16} />,
      onClick: copyPath,
    },
    {
      id: 'show-in-explorer',
      label: '在文件管理器中显示',
      icon: <FolderOpen size={16} />,
      onClick: showInExplorer,
    },
  ];

  return (
    <>
      {/* 背景遮罩 */}
      <div
        className="fixed inset-0 z-40"
        onClick={onClose}
      />
      
      {/* 菜单容器 */}
      <div
        className="fixed z-50 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-2 min-w-48"
        style={{
          left: x,
          top: y,
        }}
      >
        {menuItems.map((item) => {
          if (item.separator) {
            return (
              <div
                key={item.id}
                className="h-px bg-gray-200 dark:bg-gray-700 my-1 mx-2"
              />
            );
          }

          return (
            <button
              key={item.id}
              className={cn(
                'w-full flex items-center px-3 py-2 text-sm text-left',
                'hover:bg-gray-100 dark:hover:bg-gray-700',
                'disabled:opacity-50 disabled:cursor-not-allowed',
                item.danger && 'text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20',
                item.disabled && 'text-gray-400 dark:text-gray-600'
              )}
              disabled={item.disabled}
              onClick={item.onClick}
            >
              {/* 图标 */}
              <span className="mr-3 flex-shrink-0">
                {item.icon}
              </span>
              
              {/* 标签 */}
              <span className="flex-1">
                {item.label}
              </span>
              
              {/* 快捷键 */}
              {item.shortcut && (
                <span className="text-xs text-gray-500 dark:text-gray-400 ml-2">
                  {item.shortcut}
                </span>
              )}
            </button>
          );
        })}
      </div>
    </>
  );
};
